<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { fetchGetUserList } from '@/service/api';
import { $t } from '@/locales';
import { useTable } from '@/hooks/common/table';

defineOptions({
  name: 'UserSelectModal'
});

interface Props {
  /** selected user */
  selectedUser?: Api.SystemManage.User | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'confirm', user: Api.SystemManage.User | null): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

// 当前选中的用户
const currentSelectedUser = ref<Api.SystemManage.User | null>(null);

const { columns, data, getData, loading, mobilePagination, searchParams, resetSearchParams } = useTable({
  apiFn: fetchGetUserList,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    userName: null,
    nickName: null,
    telephone: null,
    email: null,
    status: null,
    gender: null,
    deptId: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48,
      multiple: false
    },
    {
      key: 'userName',
      title: $t('page.manage.user.userName'),
      align: 'center',
      minWidth: 100,
      width: 120
    },
    {
      key: 'nickName',
      title: $t('page.manage.user.nickName'),
      align: 'center',
      minWidth: 100,
      width: 120
    },
    {
      key: 'displayName',
      title: $t('page.manage.user.displayName'),
      align: 'center',
      minWidth: 100,
      width: 120
    },
    {
      key: 'telephone',
      title: $t('page.manage.user.telephone'),
      align: 'center',
      minWidth: 120,
      width: 140
    },
    {
      key: 'email',
      title: $t('page.manage.user.email'),
      align: 'center',
      minWidth: 150,
      width: 180
    }
  ]
});

// 选中的行键
const checkedRowKeys = ref<number[]>([]);

// 处理行选择
function handleRowSelect(rowKeys: (string | number)[]) {
  checkedRowKeys.value = rowKeys as number[];
  if (rowKeys.length > 0) {
    const selectedUserId = Number(rowKeys[0]);
    currentSelectedUser.value = data.value.find(user => user.id === selectedUserId) || null;
  } else {
    currentSelectedUser.value = null;
  }
}

// 确认选择
function handleConfirm() {
  emit('confirm', currentSelectedUser.value);
  closeModal();
}

// 取消选择
function handleCancel() {
  closeModal();
}

// 清除选择
function handleClear() {
  emit('confirm', null);
  closeModal();
}

function closeModal() {
  visible.value = false;
  currentSelectedUser.value = null;
  checkedRowKeys.value = [];
}

// 监听弹窗显示状态
watch(visible, newVisible => {
  if (newVisible) {
    // 初始化选中状态
    if (props.selectedUser) {
      currentSelectedUser.value = props.selectedUser;
      checkedRowKeys.value = [props.selectedUser.id];
    } else {
      currentSelectedUser.value = null;
      checkedRowKeys.value = [];
    }
    getData();
  }
});

// 监听数据变化，确保已选中的用户在切换页面时保持选中状态
watch(data, () => {
  if (currentSelectedUser.value) {
    // 检查当前选中的用户是否在当前页面的数据中
    const userInCurrentPage = data.value.find(user => user.id === currentSelectedUser.value?.id);
    if (userInCurrentPage) {
      // 如果在当前页面，确保选中状态正确
      checkedRowKeys.value = [currentSelectedUser.value.id];
    } else {
      // 如果不在当前页面，清空表格选中状态但保持currentSelectedUser
      checkedRowKeys.value = [];
    }
  }
});
</script>

<template>
  <NModal
    v-model:show="visible"
    preset="dialog"
    :title="$t('page.manage.dept.userSelection')"
    style="width: 800px; max-width: 90vw"
  >
    <div class="flex-col gap-16px">
      <!-- 搜索区域 -->
      <NCard size="small">
        <NForm :model="searchParams" label-placement="left" :label-width="80">
          <NGrid :cols="3" :x-gap="16">
            <NFormItemGi :label="$t('page.manage.user.userName')">
              <NInput v-model:value="searchParams.userName" :placeholder="$t('page.manage.user.form.userName')" />
            </NFormItemGi>
            <NFormItemGi :label="$t('page.manage.user.nickName')">
              <NInput v-model:value="searchParams.nickName" :placeholder="$t('page.manage.user.form.nickName')" />
            </NFormItemGi>
            <NFormItemGi>
              <NSpace>
                <NButton type="primary" @click="getData">{{ $t('common.search') }}</NButton>
                <NButton @click="resetSearchParams">{{ $t('common.reset') }}</NButton>
              </NSpace>
            </NFormItemGi>
          </NGrid>
        </NForm>
      </NCard>

      <!-- 当前选中用户提示 -->
      <NAlert v-if="currentSelectedUser" type="info" :show-icon="false" style="margin-bottom: 8px">
        <template #header>
          <span>{{ $t('page.manage.dept.currentSelected') }}: {{ currentSelectedUser.displayName }}</span>
        </template>
      </NAlert>

      <!-- 用户列表 -->
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        :loading="loading"
        :row-key="row => row.id"
        :max-height="400"
        size="small"
        remote
        :pagination="mobilePagination"
        @update:checked-row-keys="handleRowSelect"
      />
    </div>

    <template #action>
      <NSpace>
        <NButton @click="handleCancel">{{ $t('common.cancel') }}</NButton>
        <NButton @click="handleClear">{{ $t('common.clear') }}</NButton>
        <NButton type="primary" @click="handleConfirm">{{ $t('common.confirm') }}</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
